package com.example.practicetest.controller;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.example.practicetest.entity.User;
import com.example.practicetest.service.UserService;
import jakarta.servlet.ServletException;
import jakarta.servlet.ServletInputStream;
import jakarta.servlet.annotation.WebServlet;
import jakarta.servlet.http.HttpServlet;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;

/**
 * @author wushuang
 * 用户user的控制器层
 */

@WebServlet(name = "user", value = "/user/*")
public class UserController extends HttpServlet {
    UserService userService = new UserService();

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        resp.setContentType("text/html;charset=utf-8");
        resp.setCharacterEncoding("utf-8");
        String path = req.getRequestURI();
        switch (path) {
            case "/user/register"->{
                doRegister(req, resp);
            }
            case "/user/login"->{
                doLogin(req, resp);
            }
            default -> {
//                resp.getWriter().write("404");
            }
        }
    }

    private void doRegister(HttpServletRequest req, HttpServletResponse resp) throws IOException {
        JSONObject json = getJson(req);
        String username = json.getString("username");
        String password = json.getString("password");
        JSONObject jsonObject = new JSONObject();
        if(username == null || password == null){
            jsonObject.put("code", 404);
            jsonObject.put("msg", "用户名或密码不能为空");
            jsonObject.put("data", null);
            resp.getWriter().write(JSON.toJSONString(jsonObject));
            return ;
        }
        if("".equals(username.trim()) || "".equals(password.trim())){
            jsonObject.put("code", 404);
            jsonObject.put("msg", "用户名或密码不能为空");
            jsonObject.put("data", null);
            resp.getWriter().write(JSON.toJSONString(jsonObject));
            return;
        }
        User user = new User();
        user.setUsername(username);
        user.setPassword(password);
        int result = userService.register(user);
        if (result == -1) {
            jsonObject.put("code", 404);
            jsonObject.put("msg", "用户名已存在");
            jsonObject.put("data", null);
            resp.getWriter().write(JSON.toJSONString(jsonObject));
        } else if (result == 1) {
            jsonObject.put("code", 0);
            jsonObject.put("msg", "注册成功");
            jsonObject.put("data", null);
            resp.getWriter().write(JSON.toJSONString(jsonObject));
        } else {
            jsonObject.put("code", 404);
            jsonObject.put("msg", "注册失败");
            jsonObject.put("data", null);
            resp.getWriter().write(JSON.toJSONString(jsonObject));
        }
    }

    private void doLogin(HttpServletRequest req, HttpServletResponse resp) throws IOException {
        JSONObject json = getJson(req);
        String username = json.getString("username");
        String password = json.getString("password");
        JSONObject jsonObject = new JSONObject();
        if(username == null || password == null){
            jsonObject.put("code", 404);
            jsonObject.put("msg", "用户名或密码不能为空");
            jsonObject.put("data", null);
            resp.getWriter().write(JSON.toJSONString(jsonObject));
            return ;
        }
        if("".equals(username.trim()) || "".equals(password.trim())){
            jsonObject.put("code", 404);
            jsonObject.put("msg", "用户名或密码不能为空");
            jsonObject.put("data", null);
            resp.getWriter().write(JSON.toJSONString(jsonObject));
            return;
        }
        User user = new User();
        user.setUsername(username);
        user.setPassword(password);
        int result = userService.login(user);
        if (result == -1) {
            jsonObject.put("code", 404);
            jsonObject.put("msg", "用户名不存在");
            jsonObject.put("data", null);
            resp.getWriter().write(JSON.toJSONString(jsonObject));
        } else if (result == 1) {
            jsonObject.put("code", 0);
            jsonObject.put("msg", "登录成功");
            jsonObject.put("data", null);
            req.getSession().setAttribute("user",user.getUsername());
            resp.getWriter().write(JSON.toJSONString(jsonObject));
        } else {
            jsonObject.put("code", 404);
            jsonObject.put("msg", "登录失败");
            jsonObject.put("data", null);
            resp.getWriter().write(JSON.toJSONString(jsonObject));
        }
    }

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        doPost(req, resp);
    }


    /**
     * 工具类，用来把前端发送的request转换成JSONObject
     * @param request
     * @return
     */
    public static JSONObject getJson(HttpServletRequest request){
        //从前端获取输入字节流
        ServletInputStream requestInputStream = null;
        try {
            requestInputStream = request.getInputStream();
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
        //将字节流转换为字符流,并设置字符编码为utf-8
        InputStreamReader ir = null;
        try {
            ir = new InputStreamReader(requestInputStream,"utf-8");
        } catch (UnsupportedEncodingException e) {
            throw new RuntimeException(e);
        }
        //使用字符缓冲流进行读取
        BufferedReader br = new BufferedReader(ir);
        //开始拼装json字符串
        String line = null;
        StringBuilder sb = new StringBuilder();
        while(true) {
            try {
                if ((line = br.readLine()) == null) {
                    break;
                }
            } catch (IOException e) {
                throw new RuntimeException(e);
            }
            sb.append(line);
        }

        JSONObject json = JSONObject.parseObject(sb.toString());

        return (JSONObject) JSONObject.parse(String.valueOf(json));
    }
}
